function [c, c_all]=FCfindc()
% Modified 2014-08-28
% Modifed 2014-09-18 to get rid of curve subset.
% Finds the InvOLS or constant compliance region of multiple force curves.
%
% INPUT:    (Select a single file, preferably a multi-force curve)
%
% OUTPUT:   c, the averaged InvOLS constant, nm/nA
%           c_all, the vector containing each c value returned from the
%               multi-curve
%
% DATA EXPORT:
% Can be multiple signals, but will only read the first signal (DFL).
% Export ASCII.
% Values only.
% Include header.
% Delimiters for Values: Enter.
% Data unis: Original.

[data0] = FCimport();
app = data0.app;

N = numel(app);

c_all = zeros(1,N);

for jj = 1:N
  
    z = app{jj}(:,1).*1000;    %Gives z-piezo height in nm
    defnA = app{jj}(:,2);      %Deflection in nA
    
    %Find constant region of FC, and where it intersects with constant
    %compliance region (right endpoint of slope fit)
    endx = z(end-100:end);  %Samples last 100 points in the FC. Should be linear.
    endy = defnA(end-100:end);
    zero = polyfit(endx,endy,0);    %Fit points to 0-order polynomial
    indzeroz = find(defnA<zero,1,'first');     %Find index of first z point below zero
    
    %Find good zoom area for constant compliance region
    rgz = abs(z(indzeroz)-z(1));
    rgdef = abs(defnA(indzeroz)-defnA(1));
    maxx = z(indzeroz) + 0.05*rgz;
    minx = z(1) - 0.05*rgz;
    miny = defnA(indzeroz) - 0.05*rgdef;
    maxy = defnA(1) + 0.05*rgdef;
    
    %Choose endpoints of slope fit
    disp('Choose endpoints of slope fit')
    plot(z,defnA,'b.',z(indzeroz),defnA(indzeroz),'ro')
    axis([minx maxx miny maxy])
    xlabel('Displacement / nm')
    ylabel('Deflection / nA')
    pts = ginput(2);
    leftind = find(z>pts(1,1),1);
    rightind = find(z<pts(2,1),1,'last');
    
    %Define subset and fit
    zcc = z(leftind:rightind);
    defnAcc = defnA(leftind:rightind);
    p = polyfit(zcc,defnAcc,1);
    
    c_all(jj) = abs(1/p(1));
end

c = mean(c_all);